const nodemailer = require('nodemailer');
require('dotenv').config();

// 获取域名配置
const SMTP_DOMAIN = process.env.TEMPEMAIL_SMTP_DOMAIN || 'localhost';
const HTTP_DOMAIN = process.env.TEMPEMAIL_HTTP_DOMAIN || 'localhost';
const SMTP_PORTS = (process.env.TEMPEMAIL_SMTP_PORTS || '25,465,587,2525').split(',').map(port => parseInt(port.trim()));

// 获取命令行参数中的收件人邮箱
let recipient = process.argv[2] || `test@${SMTP_DOMAIN}`;
if (!recipient.includes('@')) {
    recipient = `${recipient}@${SMTP_DOMAIN}`;
}

async function tryPort(port) {
    console.log(`尝试连接端口 ${port}...`);
    
    const transporter = nodemailer.createTransport({
        host: '127.0.0.1', // 使用本地地址
        port: port,
        secure: false,
        ignoreTLS: true,
        tls: {
            rejectUnauthorized: false
        },
        debug: true, // 启用调试
        logger: true, // 启用日志
        connectionTimeout: 5000,
        greetingTimeout: 5000,
        socketTimeout: 5000,
    });

    try {
        // 验证连接
        await transporter.verify();
        console.log(`端口 ${port} 连接成功`);

        // 发送邮件
        const info = await transporter.sendMail({
            from: `test_smtp@${SMTP_DOMAIN}`,
            to: recipient,
            subject: '测试邮件',
            text: `这是一封测试邮件 - 随机数: ${Math.floor(Math.random() * 10000)}`,
            encoding: 'utf-8'
        });

        console.log(`邮件已通过端口 ${port} 发送成功:`, info.response);
        return true;
    } catch (error) {
        console.log(`端口 ${port} 尝试失败:`, error.message);
        return false;
    }
}

async function sendTestEmail() {
    console.log('开始发送测试邮件');
    console.log('目标邮箱:', recipient);
    console.log('可用端口:', SMTP_PORTS);

    // 依次尝试所有配置的端口
    for (const port of SMTP_PORTS) {
        try {
            const success = await tryPort(port);
            if (success) {
                console.log('邮件发送成功');
                process.exit(0);
            }
        } catch (error) {
            console.error(`端口 ${port} 发送失败:`, error);
        }
    }

    // 如果所有端口都失败
    console.error('所有端口尝试均失败');
    process.exit(1);
}

// 执行发送
sendTestEmail().catch(error => {
    console.error('发送过程出错:', error);
    process.exit(1);
}); 